package cn.moziware.falldetectordemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import java.util.Objects;

import cn.moziware.falldetectordemo.databinding.ActivityMainBinding;
import io.moziware.falldetectorlibrary.FallDetectorInterface;
import kotlin.Unit;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    FallDetectorInterface fallDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        fallDetector = new FallDetectorInterface(getApplication());
        fallDetector.bindService( () -> {
            reloadAlertActivityData();
            return Unit.INSTANCE;
        });
        binding.buttonSet.setOnClickListener(view -> {
            String alertPackage = fallDetector.getAlertActivityPackage();
            if (!Objects.equals(alertPackage, getPackageName())){
                fallDetector.registerAlertActivity(TestActivity.class);
            } else {
                fallDetector.unregisterAlertActivity();
            }
            reloadAlertActivityData();
        });
        binding.buttonTest.setOnClickListener(view -> fallDetector.sendTestAlert());
    }

    private void reloadAlertActivityData() {
        String alertPackage = fallDetector.getAlertActivityPackage();
        binding.alertPackage.setText((alertPackage == null || alertPackage.isEmpty())?getString(R.string.not_registered):alertPackage);
        String alertActivity = fallDetector.getAlertActivityName();
        binding.alertActivity.setText((alertActivity == null || alertActivity.isEmpty())?getString(R.string.not_registered):alertActivity);
        binding.buttonSet.setText((!Objects.equals(alertPackage, this.getPackageName()))?getString(R.string.register_fall_handler):getString(R.string.unregister_handler));
    }

    @Override
    protected void onResume() {
        super.onResume();
        reloadAlertActivityData();
    }

    @Override
    protected void onDestroy() {
        fallDetector.unbindService();
        super.onDestroy();
    }
}